package com.ruoyi.web.controller.system;

import cn.hutool.core.bean.BeanUtil;
import com.angel.mongodb.utils.Wraps;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysConfig;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.core.service.impl.BaseService;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.web.viewObject.SysConfigVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @description: 参数配置 信息操作处理
 * @author: gankench@gmail.com
 * @time: 4/10/21 6:49 PM
 */
@RestController
@RequestMapping("/system/config")
public class SysConfigController extends BaseController<SysConfigVo, String> {
    @Autowired
    private BaseService baseService;
    @Autowired
    private RedisCache redisCache;

    /**
     * 获取参数配置列表
     */
    @PreAuthorize("@ss.hasPermi('system:config:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysConfigVo config) {
        SysConfig sysConfig = BeanUtil.copyProperties(config, SysConfig.class);
        List<SysConfigVo> list = baseService.findPage(Wraps.buildBasePageQuery(sysConfig, TableSupport.buildPageRequest()), SysConfig.class)
                .stream()
                .map(item -> BeanUtil.copyProperties(item, SysConfigVo.class))
                .collect(Collectors.toList());
        return getDataTable(list);
    }

    @Log(title = "参数管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:config:export')")
    @GetMapping("/export")
    public AjaxResult export(SysConfig config) {
        SysConfig sysConfig = BeanUtil.copyProperties(config, SysConfig.class);
        List<SysConfigVo> list = baseService.findPage(Wraps.buildBasePageQuery(sysConfig, TableSupport.buildPageRequest()), SysConfig.class)
                .stream()
                .map(item -> BeanUtil.copyProperties(item, SysConfigVo.class))
                .collect(Collectors.toList());
        ExcelUtil<SysConfigVo> util = new ExcelUtil<SysConfigVo>(SysConfigVo.class);
        return util.exportExcel(list, "参数数据");
    }

    /**
     * 根据参数编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:config:query')")
    @GetMapping(value = "/{configId}")
    public AjaxResult getInfo(@PathVariable String configId) {
        return AjaxResult.success(baseService.findById(configId, SysConfig.class));
    }

    /**
     * 根据参数键名查询参数值
     */
    @GetMapping(value = "/configKey/{configKey}")
    public AjaxResult getConfigKey(@PathVariable String configKey) {
        SysConfig sysConfig = SysConfig.builder().configKey(configKey).build();
        return AjaxResult.success(baseService.findListByQuery(Wraps.andWrapper(sysConfig), SysConfig.class));
    }

    /**
     * 新增参数配置
     */
    @PreAuthorize("@ss.hasPermi('system:config:add')")
    @Log(title = "参数管理", businessType = BusinessType.INSERT)
    @PostMapping
    @RepeatSubmit
    public AjaxResult add(@Validated @RequestBody SysConfig config) {
        if (UserConstants.NOT_UNIQUE.equals(baseService.findCountByQuery(Wraps.andWrapper(config), SysConfig.class))) {
            return AjaxResult.error("新增参数'" + config.getConfigName() + "'失败，参数键名已存在");
        }
        config.setCreateBy(SecurityUtils.getUsername());
        baseService.save(config);
        return toAjax(true);
    }

    /**
     * 修改参数配置
     */
    @PreAuthorize("@ss.hasPermi('system:config:edit')")
    @Log(title = "参数管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysConfig config) {
        if (UserConstants.NOT_UNIQUE.equals(baseService.findCountByQuery(Wraps.andWrapper(config), SysConfig.class))) {
            return AjaxResult.error("修改参数'" + config.getConfigName() + "'失败，参数键名已存在");
        }
        config.setUpdateBy(SecurityUtils.getUsername());
        baseService.updateAllColumnById(config);
        return toAjax(true);
    }

    /**
     * 删除参数配置
     */
    @PreAuthorize("@ss.hasPermi('system:config:remove')")
    @Log(title = "参数管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{configIds}")
    public AjaxResult remove(@PathVariable List<String> configIds) {
        return toAjax(baseService.deleteByIds(configIds, SysConfig.class).intValue());
    }

    /**
     * 清空缓存
     */
    @PreAuthorize("@ss.hasPermi('system:config:remove')")
    @Log(title = "参数管理", businessType = BusinessType.CLEAN)
    @DeleteMapping("/clearCache")
    public AjaxResult clearCache() {
        Collection<String> keys = redisCache.keys(Constants.SYS_CONFIG_KEY + "*");
        redisCache.deleteObject(keys);
        return AjaxResult.success();
    }
}
